var WebSocket = require('ws');

function WSServerCreate(ports) {
	var WebSocketServer = WebSocket.Server,
		wss = new WebSocketServer({
			port: ports,
			host: '0.0.0.0' //解决局域网连接不了
		});

	//wss.setTimeout(0);
	//wss.setNoDelay(true);

	console.log('WebSocket服务器已经启动.');

	var uuid = require('node-uuid');
	var clients = [];
    
    //消息发送
    //
	function wsSend(type, client_uuid, nickname, message) {
		for(var i = 0; i < clients.length; i++) {
			var clientSocket = clients[i].ws;
			if(clientSocket.readyState === WebSocket.OPEN) {
				clientSocket.send(JSON.stringify({
					"type": type,
					"id": client_uuid,
					"nickname": nickname,
					"message": message
				}));
			}
		}
	}

	var clientIndex = 1;
	wss.on('connection', function(ws) {

		if(clients.length<=0){
			clientIndex = 1;
		}else{
			clientIndex=clients.length+1;
		}
		var client_uuid = uuid.v4();
		var nickname = "匿名用户" + clientIndex;
		clientIndex += 1;
		clients.push({
			"id": client_uuid,
			"ws": ws,
			"nickname": nickname
		});
		console.log('client [%s] connected', client_uuid);
		var connect_message = nickname + " 已经进入聊天室";
		wsSend("notification", client_uuid, nickname, connect_message);

		ws.on('message', function(message) {
			if(message.indexOf('/nick') === 0) {
				var nickname_array = message.split(' ');
				if(nickname_array.length >= 2) {
					var old_nickname = nickname;
					nickname = nickname_array[1];
					var nickname_message = "用户 " + old_nickname + " 已经改名为 " + nickname;
					wsSend("nick_update", client_uuid, nickname, nickname_message);
				}
			} else {
				wsSend("message", client_uuid, nickname, message);
			}
		});

		var closeSocket = function(customMessage) {
			for(var i = 0; i < clients.length; i++) {
				if(clients[i].id == client_uuid) {
					var disconnect_message;
					if(customMessage) {
						disconnect_message = customMessage;
					} else {
						disconnect_message = nickname + " 离开聊天室";
					}
					wsSend("notification", client_uuid, nickname, disconnect_message);
					clients.splice(i, 1);
				}
			}
		};
		
		ws.on('close', function() {
			closeSocket();
		});
		process.on('SIGINT', function() {
			console.log("Closing things");
			closeSocket('Server has disconnected');
			process.exit();
		});
	});

}

module.exports = WSServerCreate;